package com.xxmw.transaction.common.utils.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * httpclient 使用
 * @author luowenliang
 * @since 2020/2/9 15:32
 */
@Slf4j
public class HttpClientUtil {

    public static String get (String url) {
        return get(url, new ArrayList<>());
    }

    public static String get (String url, List<NameValuePair> params) {
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (null != params && params.size() > 0) {
                uriBuilder.setParameters(params);
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            return request(httpGet);
        } catch (URISyntaxException e) {
            log.error("请求URL异常", e);
        }
        return null;
    }

    public static String get (String url, HttpHeader header) {
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeaders(header.getHeaders());
            return request(httpGet);
        } catch (URISyntaxException e) {
            log.error("请求URL异常：{}", url);
        }
        return null;
    }

    public static String post (String url) {
        HttpPost httpPost = new HttpPost(url);
        return request(httpPost);
    }

    public static String post (String url, String params) {
        return post(url, null, params);
    }

    public static String post (String url, HttpHeader header) {
        return post(url, header, null);
    }

    public static String post (String url, HttpHeader header, String params) {
        HttpPost httpPost = new HttpPost(url);
        // 解决中文乱码问题
        if (StringUtils.isNotBlank(params)) {
            StringEntity entity = new StringEntity(params, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }
        if (null != header) {
            httpPost.setHeaders(header.getHeaders());
        }
        return request(httpPost);
    }

    public static String postByBody (String url, HttpHeader header, Map<String, String> params) {
        List<BasicNameValuePair> pair =new ArrayList<>();

        for (Map.Entry<String,String> entry:
                params.entrySet()) {
            pair.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }

        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(pair));
        } catch (UnsupportedEncodingException e) {
            log.info("参数注入失败");
        }
        if (null != header) {
            httpPost.setHeaders(header.getHeaders());
        }
        return request(httpPost);
    }

    public static String postNotUTF_8 (String url, HttpHeader header, String params) {
        HttpPost httpPost = new HttpPost(url);
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(params, "GBK");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        if (null != header) {
            httpPost.setHeaders(header.getHeaders());
        }
        return request(httpPost);
    }

    public static String post(String url, List<NameValuePair> params) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);
        if (null != params && params.size() > 0) {
            uriBuilder.setParameters(params);
        }
        HttpPost httpPost = new HttpPost(uriBuilder.build());
        return request(httpPost);
    }

    private static String request (HttpUriRequest request) {
        CloseableHttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build();
        String res = null;
        try {
            HttpResponse resp = client.execute(request);
            String entity = EntityUtils.toString(resp.getEntity());
            // log.info("HttpResponse Entity: {}", entity);
            return entity;
//            if (resp.getStatusLine().getStatusCode() == 200) {
//                HttpEntity he = resp.getEntity();
//                res = EntityUtils.toString(he, "UTF-8");
//            }
        } catch (Exception e) {
            log.error("请求异常",e);
        }
        return res;
    }
}
